package com.moke.xlsx
{
	import flash.utils.ByteArray;

	public class XMLUtil
	{
		public static function getSheetListFromWorkbook(bytes:ByteArray):Array
		{
			var xml:XML = XML(bytes.readUTFBytes(bytes.bytesAvailable));
			var ns:Namespace = xml.namespace();
			var sheetList:XMLList = xml.ns::sheets.ns::sheet;
			var arr:Array = [];
			for each(var item:XML in sheetList)
			{
				var sheet:Sheet = new Sheet();
				sheet.id = String(item.@sheetId);
				sheet.name = String(item.@name);
				arr.push(sheet);
			}
			return arr;
		}
		public static function parseRow(sheetValues:Array,xmlList:XMLList, ns:Namespace, sharedStrings:Array):void
		{
			for each (var item:XML in xmlList)
			{
				var rowIndex:int = int(item.@r) - 1;
				var cols:Object = {};
				var colList:XMLList = item.ns::c;
				for each (var colListItem:XML in colList)
				{
					var colLetter:String = ExcelUtil.getLetter(colListItem.@r);
					var t:String = colListItem.@t;
					var v:String = colListItem.ns::v[0];
					if (t == "s")
					{
						cols[colLetter] = sharedStrings[int(v)];
					}
					else
					{
						if(v != null)
						{
							cols[colLetter] = v;
						}
					}
				}
				sheetValues[rowIndex] = cols;
			}
		}
		
		public static function getSharedStrings(bytes:ByteArray):Array
		{
			bytes.position = 0;
			var xml:XML = XML(bytes.readUTFBytes(bytes.bytesAvailable));
			var ns:Namespace = xml.namespace();
			var valueList:XMLList = xml.ns::si;
			var values:Array = [];
			for each (var valueListItem:XML in valueList)
			{
				var textList:XMLList = valueListItem..ns::t;
				var tv:String = "";
				for each (var textListItem:XML in textList)
				{
					tv += textListItem.toString();
				}
				
				values.push(tv);
			}
			return values;
		}
		
		public static function mergeCell(sheetValues:Array,xmlList:XMLList):void
		{
			for each (var item:XML in xmlList)
			{
				var refArr:Array = String(item.@ref).split(":");
				var startInfo:CellPositionInfo = ExcelUtil.getCellPosition(refArr[0]);
				var endInfo:CellPositionInfo = ExcelUtil.getCellPosition(refArr[1]);
				var sv:Object;
				if (sheetValues[startInfo.rowIndex] != null)
				{
					sv = sheetValues[startInfo.rowIndex][startInfo.colLetter];
					if(sv == null)
					{
						continue ;
					}
				}
				for (var i:int = startInfo.rowIndex; i <= endInfo.rowIndex; i++)
				{
					for (var j:int = startInfo.colIndex; j <= endInfo.colIndex; j++)
					{
						if (sheetValues[i] == null)
						{
							sheetValues[i] = {};
						}
						sheetValues[i][ExcelUtil.ColIntToLetter(j)] = sv;
					}
				}
			}
		}
	}
}